package com.cloudeasy.server.controller;

import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.user.PermissionVO;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.api.vo.oauth.OAuthUserEnableRolesVO;
import com.cloudeasy.server.po.Role;
import com.cloudeasy.server.po.User;
import com.cloudeasy.server.po.UserRole;
import com.cloudeasy.server.service.RoleService;
import com.cloudeasy.server.service.UserRoleService;
import com.cloudeasy.server.service.UserService;
import com.cloudeasy.server.util.OAuthUtil;
import com.cloudeasy.server.util.PermissionUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/oauth")
public class OAuthController {

    private final UserService userService;
    private final UserRoleService userRoleService;
    private final RoleService roleService;

    public OAuthController(UserService userService, UserRoleService userRoleService, RoleService roleService) {
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.roleService = roleService;
    }

    /**
     * 获取用户拥有的所有可用角色
     * @param account 账号
     * @return {@link Result<OAuthUserEnableRolesVO>}
     */
    @GetMapping("/{account:\\S+}/role")
    Result<OAuthUserEnableRolesVO> getUserEnableRole(@PathVariable("account") String account) {
        User user = userService.getByAccount(account);
        List<UserRole> userRoles = userRoleService.getEnableListByUserId(user.getId());
        List<String> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roles = roleService.getEnableListByIds(roleIds);
        return ResultUtil.success(OAuthUtil.compose(user, roles, userRoles));
    }


    /**
     * 获取用户拥有的所有可用权限
     *
     * @param account 账号
     * @return {@link PermissionVO}列表的{@link Result}
     */
    @GetMapping("/{account:\\S+}/permission")
    Result<List<PermissionVO>> getUserEnablePermission(@PathVariable("account") String account) {
        return ResultUtil.success(PermissionUtil.convert(userService.getEnablePermission(account)));
    }
}
